<?php

namespace App\Http\Services\Queue;


use App\Http\Model\Queue;
use App\Http\Services\Message\MessageServices;
use Illuminate\Support\Facades\DB;

class QueueServices
{
    protected $queueModel = null;

    public function __construct()
    {
        $this -> queueModel = new Queue();

    }


    public function push($name, $runParams,$runTime=0):bool
    {
        $data = [];
        $data['name'] = $name;
        $data['state'] = Queue::QUEUE_STATE_RUN;
        $data['is_lock'] = Queue::QUEUE_UNLOCK;
        $data['run_time'] = $runTime>0 ? $runTime : time();
        $data['params'] = json_encode( $runParams );
        return $this->queueModel -> add($data);
    }

    public function pop($queueName)
    {
        return $this->queueModel -> getQueuePop($queueName);
    }

    public function queueLock($queueId)
    {
        return $this->queueModel -> queueLock($queueId);
    }

    public function queueEnd($queueId)
    {
        return $this->queueModel -> queueEnd($queueId);
    }



    public function handle($queueInfo):bool
    {

        $state = true;
        $msg = 'OK';
        $error = '';

        try {
            $taskId = $queueInfo['id'];
            $taskName = $queueInfo['name'];
            $queueParams = json_decode($queueInfo['params'], 1);

            $taskObj = ProcessService::Instance($taskName);
            $res = $taskObj -> handle($queueParams);
            if (!$res){
                throw new \Exception('业务运行失败');
            }
        } catch (\Exception $e) {
            $state = false;
            $msg = $e->getMessage();
            $error = $e->getFile() . ' ' . $e->getLine();
            $WebHook = config("message.module.robotWarn");
            MessageServices::text($WebHook, '[异常]执行队列任务taskId:'.$taskId. '-taskName:'.$taskName . '-msg:' . $msg);
        };

        write_log(
            'QueueServices'.(isCli()?'-cli':''),
            ($state?'[INFO]':'[ERROR]') . ' task:'.$taskName,
            ['args'=>func_get_args(), 'msg'=>$msg, 'error'=>$error]
        );

        return $state;
    }





}

